﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace WEALTH.Manager.User
{
    public partial class UserList : BasePage
    {
        private UserFilter userFilter = new UserFilter();
        private ExcuteDao userManage = new ExcuteDao();

        //public int pageSize, pageIndex, pageCount, recordCount;

        /// <summary>
        /// 页面初始化事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["UrlType"] != null && Request.QueryString["UrlType"].Equals("menu"))
            {
                Session["SortExpression_UserList"] = null;
                Session["SortDirection_UserList"] = null;
                Session["User_ID"] = null;
                Session["User_Name"] = null;
                Session["User_Mail"] = null;
                Session["User_Tel"] = null;
                Session["User_status"] = null;
                Session["Role_Name"] = null;
            }

            if (Session["UrlType"] != null)
            {
                if (Session["UrlType"].Equals("EditUser"))
                {
                    setSessionData();
                    SetValue();

                    if (Session["UserListIndex"] != null && string.IsNullOrEmpty(Request.QueryString["pageIndex"]))
                    {
                        gvUser.PageIndex = (int)Session["UserListIndex"];
                    }

                    Session["UrlType"] = null;
                }
            }
            if (!string.IsNullOrEmpty(Request.QueryString["pageIndex"]))
            {
                string pageIndex = Request.QueryString["pageIndex"];
                int index = Convert.ToInt32(pageIndex);
                gvUser.PageIndex = index;

                Session["UserListIndex"] = index;

                setSessionData();
            }
            //设置分页状态
            if (Session["SortExpression_UserList"] != null)
            {
                this.gvUser.Attributes["SortExpression_UserList"] = Session["SortExpression_UserList"].ToString();
                this.gvUser.Attributes["SortDirection_UserList"] = Session["SortDirection_UserList"].ToString();
                setSortColumnStyle(this.gvUser, Session["SortExpression_UserList"].ToString(), Session["SortDirection_UserList"].ToString());
            }
            //setSortColumnStyle(gvUser, this.gvUser.Attributes["SortExpression_UserList"].ToString(),
            //     this.gvUser.Attributes["SortDirection_UserList"].ToString());
            if (!IsPostBack)
            {
                ViewState["UserAll"] = userManage.Get_UserALL(userFilter);

                //初次加载清空分页状态
                //if (string.IsNullOrEmpty(Request.QueryString["pageIndex"]) && Session["UrlType"] == null)
                //{
                //    Session["SortExpression_UserList"] = null;
                //    Session["SortDirection_UserList"] = null;
                //}
                SearchUserBindData();
            }
        }

        private void setSessionData()
        {
            //检索条件记录
            if (Session["User_ID"] != null)
            {
                txtuserid.Text = SpecialCharHandler.HtmlDiscode(Session["User_ID"].ToString());
            }
            if (Session["User_Name"] != null)
            {
                txtusername.Text = SpecialCharHandler.HtmlDiscode(Session["User_Name"].ToString());

            }
            if (Session["User_Mail"] != null)
            {
                txtEmail.Text = SpecialCharHandler.HtmlDiscode(Session["User_Mail"].ToString());

            }
            if (Session["User_Tel"] != null)
            {
                txtTel.Text = SpecialCharHandler.HtmlDiscode(Session["User_Tel"].ToString());

            }
            if (Session["User_status"] != null)
            {
                ddlStatus.SelectedValue = Session["User_status"].ToString();

            }

            if (Session["Role_Name"] != null)
            {
                string[] role_code = ((string)Session["Role_Name"]).Replace("'", "").Split(',');
                userFilter.Role_Name = Session["Role_Name"].ToString();
                DataTable dtrole = new DataTable();
                dtrole.Columns.Add("role_code");
                for (int i = 0; i < role_code.Length; i++)
                {
                    DataRow dr = dtrole.NewRow();
                    dr[0] = role_code[i];
                    dtrole.Rows.Add(dr);
                }
                Session["dtrole"] = dtrole;
            }

            if (Session["UserListIndex"] != null)
            {
                gvUser.PageIndex = (int)Session["UserListIndex"];
            }
        }
        #region 用户列表事件

        /// <summary>
        /// 用户列表数据加载时触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvUser_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("id", e.Row.RowIndex.ToString());
                e.Row.Attributes.Add("onKeyDown", "SelectRow();");
                e.Row.Attributes.Add("onClick", "MarkRow(" + e.Row.RowIndex.ToString() + ");");
                ((HyperLink)e.Row.Cells[0].Controls[0]).NavigateUrl = "../User/EditUser.aspx?UserID="
                    + SpecialCharHandler.HtmlDiscode(((HyperLink)e.Row.Cells[0].Controls[0]).Text).Replace("&", "amp;");
                ((HyperLink)e.Row.Cells[3].Controls[0]).NavigateUrl = "mailto:" + ((HyperLink)e.Row.Cells[3].Controls[0]).Text;

                ((HyperLink)e.Row.Cells[0].Controls[0]).Text = SpecialCharHandler.HtmlDiscode(((HyperLink)e.Row.Cells[0].Controls[0]).Text);
                e.Row.Cells[1].Text = SpecialCharHandler.HtmlDiscode(e.Row.Cells[1].Text);
                e.Row.Cells[2].Text = SpecialCharHandler.HtmlDiscode(e.Row.Cells[2].Text);
                ((HyperLink)e.Row.Cells[3].Controls[0]).Text = SpecialCharHandler.HtmlDiscode(((HyperLink)e.Row.Cells[3].Controls[0]).Text);


            }
        }
        /// <summary>
        /// 用户状态按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvbtnStatus_Click(object sender, EventArgs e)
        {

        }

        #endregion

        /// <summary>
        /// 搜索按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            userFilter = new UserFilter();
            SetValue();

            string strRoleCode = string.Empty;
            foreach (CheckBoxList cbl in cblRole.Controls)
            {
                foreach (ListItem ckRole in cbl.Items)
                {
                    if (ckRole.Selected)
                    {
                        strRoleCode += "'" + ckRole.Value + "',";

                    }
                }
            }
            userFilter.Role_Name = strRoleCode.TrimEnd(',');

            ViewState.Clear();
            ViewState["UserAll"] = userManage.Get_UserALL(userFilter);
            //清空分页状态
            Session["SortExpression_UserList"] = null;
            Session["SortDirection_UserList"] = null;

            //检索条件记录
            Session["User_ID"] = userFilter.User_ID;
            Session["User_Name"] = userFilter.User_Name;
            Session["User_Mail"] = userFilter.User_Mail;
            Session["User_Tel"] = userFilter.User_Tel;
            Session["User_status"] = userFilter.User_status;
            Session["Role_Name"] = userFilter.Role_Name;

            SearchUserBindData();

        }

        private void SetValue()
        {
            userFilter.User_ID = SpecialCharHandler.HtmlEncode(txtuserid.Text.TrimEnd());
            userFilter.User_Name = SpecialCharHandler.HtmlEncode(txtusername.Text.TrimEnd());
            userFilter.User_Mail = SpecialCharHandler.HtmlEncode(txtEmail.Text.TrimEnd());
            userFilter.User_Tel = SpecialCharHandler.HtmlEncode(txtTel.Text.TrimEnd());
            userFilter.User_status = ddlStatus.SelectedValue;
        }

        /// <summary>
        /// 选择页面功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvUser_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.gvUser.PageIndex = e.NewPageIndex;
            pageIndex = e.NewPageIndex;
            Session["UserListIndex"] = pageIndex;
            SearchUserBindData();
        }

        /// <summary>
        /// GridView排序事件
        /// </summary>
        protected void gvUser_Sorting(object sender, GridViewSortEventArgs e)
        {
            // 从事件参数获取排序数据列
            string SortExpression_UserList = e.SortExpression.ToString();
            //// 假定为排序方向为“顺序”
            string SortDirection_UserList = "ASC";
            // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
            if (SortExpression_UserList == this.gvUser.Attributes["SortExpression_UserList"])
            {
                //获得下一次的排序状态
                SortDirection_UserList = (this.gvUser.Attributes["SortDirection_UserList"].ToString() == SortDirection_UserList ? "DESC" : "ASC");
            }
            // 重新设定GridView排序数据列及排序方向
            this.gvUser.Attributes["SortExpression_UserList"] = SortExpression_UserList;
            this.gvUser.Attributes["SortDirection_UserList"] = SortDirection_UserList;
            //记录分页状态
            Session["SortExpression_UserList"] = SortExpression_UserList;
            Session["SortDirection_UserList"] = SortDirection_UserList;

            setSortColumnStyle(this.gvUser, SortExpression_UserList, SortDirection_UserList);
            this.SearchUserBindData();
        }

        /// <summary>
        /// 绑定到GridView
        /// </summary>
        private void SearchUserBindData()
        {
            // 获取GridView排序数据列及排序方向
            string SortExpression_UserList = this.gvUser.Attributes["SortExpression_UserList"];
            string SortDirection_UserList = this.gvUser.Attributes["SortDirection_UserList"];
            // 调用业务数据获取方法
            DataTable dtBind = (DataTable)ViewState["UserAll"];

            //页面数据总数
            recordCount = dtBind.Rows.Count;

            // 根据GridView排序数据列及排序方向设置显示的默认数据视图
            if ((!string.IsNullOrEmpty(SortExpression_UserList)) && (!string.IsNullOrEmpty(SortDirection_UserList)))
            {
                dtBind.DefaultView.Sort = string.Format("{0} {1}", SortExpression_UserList, SortDirection_UserList);
            }
            // GridView绑定并显示数据
            this.gvUser.DataSource = dtBind;
            this.gvUser.DataBind();

            pageCount = gvUser.PageCount;
            pageIndex = gvUser.PageIndex;

        }
        protected void gvUser_DataBound(object sender, EventArgs e)
        {
            if (Session["Edit_UserID"] != null)
            {
                foreach (GridViewRow gvr in gvUser.Rows)
                {
                    if (((HyperLink)gvr.Cells[0].Controls[0]).Text.Equals(
                        SpecialCharHandler.HtmlDiscode(Session["Edit_UserID"].ToString())))
                    {
                        //gvUser.SelectedIndex = gvr.RowIndex;
                        //gvUser.Rows[gvr.RowIndex].BackColor = System.Drawing.Color.FromName("#D8EBF0");
                        ClientScript.RegisterStartupScript(GetType(), "SelectRow", "<script>MarkRow(" + gvr.RowIndex + "); </script>");

                    }
                }
                Session["Edit_UserID"] = null;
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {

            int isok = 0;

            bool ischecked = false;
            for (int i = 0; i <= gvUser.Rows.Count - 1; i++)
            {
                CheckBox CheckBox = (CheckBox)gvUser.Rows[i].FindControl("chkdelete");
                if (CheckBox.Checked == true)
                {
                    string userid = ((HyperLink)gvUser.Rows[i].Cells[0].Controls[0]).Text;
                    isok = userManage.Delete_User(userid);
                    ischecked = true;
                }
                
            }
            if (ischecked)
            {
                ischecked = false;
                if (isok == -1)
                {
                    ShowMsg("删除用户成功！", 0);
                    ViewState["UserAll"] = userManage.Get_UserALL(userFilter);
                    SearchUserBindData();
                }
                else
                {
                    ShowMsg("删除用户失败！", 1);
                }
            }
        }
    }
}